from flask import Blueprint, jsonify, request
from app.models.Skillc2 import CampusActivity, ActivityComment, User
from app import db
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime

activity_bp = Blueprint('activity', __name__)

@activity_bp.route('/campus/activities', methods=['GET'])
def get_campus_activities():
    """获取校园动态列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        
        activities = CampusActivity.query.order_by(CampusActivity.CreateTime.desc()).paginate(page=page, per_page=per_page)
        
        return jsonify({
            'status': 'success',
            'data': {
                'items': [activity.to_dict() for activity in activities.items],
                'total': activities.total,
                'pages': activities.pages,
                'current_page': page,
                'has_next': activities.has_next,
                'has_prev': activities.has_prev
            }
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@activity_bp.route('/campus/activities/<int:activity_id>', methods=['GET'])
def get_campus_activity(activity_id):
    """获取校园动态详情"""
    try:
        activity = CampusActivity.query.get_or_404(activity_id)
        
        return jsonify({
            'status': 'success',
            'data': activity.to_dict()
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@activity_bp.route('/campus/activities', methods=['POST'])
@jwt_required()
def create_campus_activity():
    """创建校园动态"""
    try:
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404
            
        data = request.get_json()
        
        # 验证必要字段
        required_fields = ['title', 'content']
        if not all(field in data for field in required_fields):
            return jsonify({
                'status': 'error',
                'message': '缺少必要字段'
            }), 400
        
        activity = CampusActivity(
            UserId=current_user_id,
            Title=data['title'],
            Content=data['content'],
            Image1=data.get('image1'),
            Image2=data.get('image2')
        )
        
        db.session.add(activity)
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '校园动态创建成功',
            'data': activity.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@activity_bp.route('/campus/activities/<int:activity_id>', methods=['PUT'])
@jwt_required()
def update_campus_activity(activity_id):
    """更新校园动态"""
    try:
        current_user_id = int(get_jwt_identity())
        
        activity = CampusActivity.query.get_or_404(activity_id)
        
        # 验证是否是动态的创建者
        if activity.UserId != current_user_id:
            return jsonify({
                'status': 'error',
                'message': '只有创建者可以修改动态'
            }), 403
            
        data = request.get_json()
        
        # 更新字段
        if 'title' in data:
            activity.Title = data['title']
        if 'content' in data:
            activity.Content = data['content']
        if 'image1' in data:
            activity.Image1 = data['image1']
        if 'image2' in data:
            activity.Image2 = data['image2']
        
        activity.UpdateTime = datetime.now()
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '校园动态更新成功',
            'data': activity.to_dict()
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@activity_bp.route('/campus/activities/<int:activity_id>', methods=['DELETE'])
@jwt_required()
def delete_campus_activity(activity_id):
    """删除校园动态"""
    try:
        current_user_id = int(get_jwt_identity())
        
        activity = CampusActivity.query.get_or_404(activity_id)
        
        # 验证是否是动态的创建者
        if activity.UserId != current_user_id:
            return jsonify({
                'status': 'error',
                'message': '只有创建者可以删除动态'
            }), 403
            
        db.session.delete(activity)
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '校园动态删除成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@activity_bp.route('/campus/activities/<int:activity_id>/like', methods=['POST'])
@jwt_required()
def like_campus_activity(activity_id):
    """点赞校园动态"""
    try:
        activity = CampusActivity.query.get_or_404(activity_id)
        
        activity.LikeCount += 1
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '点赞成功',
            'data': {
                'like_count': activity.LikeCount
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@activity_bp.route('/campus/activities/<int:activity_id>/favorite', methods=['POST'])
@jwt_required()
def favorite_campus_activity(activity_id):
    """收藏校园动态"""
    try:
        activity = CampusActivity.query.get_or_404(activity_id)
        
        activity.FavoriteCount += 1
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '收藏成功',
            'data': {
                'favorite_count': activity.FavoriteCount
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@activity_bp.route('/campus/activities/<int:activity_id>/comments', methods=['GET'])
def get_activity_comments(activity_id):
    """获取校园动态评论列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        
        # 验证动态是否存在
        activity = CampusActivity.query.get_or_404(activity_id)
        
        comments = ActivityComment.query.filter_by(ActivityId=activity_id).order_by(ActivityComment.CreateTime.desc()).paginate(page=page, per_page=per_page)
        
        return jsonify({
            'status': 'success',
            'data': {
                'items': [comment.to_dict() for comment in comments.items],
                'total': comments.total,
                'pages': comments.pages,
                'current_page': page,
                'has_next': comments.has_next,
                'has_prev': comments.has_prev
            }
        })
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@activity_bp.route('/campus/activities/<int:activity_id>/comments', methods=['POST'])
@jwt_required()
def create_activity_comment(activity_id):
    """创建校园动态评论"""
    try:
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        if not user:
            return jsonify({
                'status': 'error',
                'message': '用户不存在'
            }), 404
            
        # 验证动态是否存在
        activity = CampusActivity.query.get_or_404(activity_id)
        
        data = request.get_json()
        
        # 验证必要字段
        if not data or 'content' not in data:
            return jsonify({
                'status': 'error',
                'message': '缺少评论内容'
            }), 400
        
        comment = ActivityComment(
            ActivityId=activity_id,
            UserId=current_user_id,
            Content=data['content']
        )
        
        db.session.add(comment)
        
        # 更新动态的评论数
        activity.CommentCount += 1
        
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '评论创建成功',
            'data': comment.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@activity_bp.route('/campus/comments/<int:comment_id>', methods=['PUT'])
@jwt_required()
def update_activity_comment(comment_id):
    """更新校园动态评论"""
    try:
        current_user_id = int(get_jwt_identity())
        
        comment = ActivityComment.query.get_or_404(comment_id)
        
        # 验证是否是评论的创建者
        if comment.UserId != current_user_id:
            return jsonify({
                'status': 'error',
                'message': '只有创建者可以修改评论'
            }), 403
            
        data = request.get_json()
        
        # 验证必要字段
        if not data or 'content' not in data:
            return jsonify({
                'status': 'error',
                'message': '缺少评论内容'
            }), 400
        
        comment.Content = data['content']
        comment.UpdateTime = datetime.now()
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '评论更新成功',
            'data': comment.to_dict()
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@activity_bp.route('/campus/comments/<int:comment_id>', methods=['DELETE'])
@jwt_required()
def delete_activity_comment(comment_id):
    """删除校园动态评论"""
    try:
        current_user_id = int(get_jwt_identity())
        
        comment = ActivityComment.query.get_or_404(comment_id)
        
        # 验证是否是评论的创建者
        if comment.UserId != current_user_id:
            return jsonify({
                'status': 'error',
                'message': '只有创建者可以删除评论'
            }), 403
            
        # 获取关联的动态
        activity = CampusActivity.query.get(comment.ActivityId)
        if activity:
            # 更新动态的评论数
            activity.CommentCount = max(0, activity.CommentCount - 1)
        
        db.session.delete(comment)
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '评论删除成功'
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@activity_bp.route('/campus/comments/<int:comment_id>/like', methods=['POST'])
@jwt_required()
def like_activity_comment(comment_id):
    """点赞校园动态评论"""
    try:
        comment = ActivityComment.query.get_or_404(comment_id)
        
        comment.LikeCount += 1
        db.session.commit()
        
        return jsonify({
            'status': 'success',
            'message': '点赞成功',
            'data': {
                'like_count': comment.LikeCount
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500 